import pygame
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 1024
screen_height = 512
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("飞机大战")

# 加载背景图片
background = pygame.image.load(r'C:\Users\hp\Desktop\背景.png')

# 加载飞机图片
aircraft = pygame.image.load(r'C:\Users\hp\Desktop\飞机.png')
aircraft_rect = aircraft.get_rect()
aircraft_rect.x = (screen_width - aircraft_rect.width) // 2
aircraft_rect.y = screen_height - aircraft_rect.height - 50

# 设置敌机
enemy = pygame.image.load(r'C:\Users\hp\Desktop\敌人1.png')
enemy_rect = enemy.get_rect()
enemy_rect.x = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.y = -enemy_rect.height

# 设置速度
aircraft_speed = 5
enemy_speed = 2

# 游戏循环
running = True
while running:
    # 绘制背景
    screen.blit(background, (0, 0))

    # 绘制飞机
    screen.blit(aircraft, aircraft_rect)

    # 绘制敌机
    screen.blit(enemy, enemy_rect)

    # 更新屏幕
    pygame.display.update()

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 屏幕与背景自适应
        # 缩放图片到窗口大小
        image = pygame.transform.scale(background, (screen_width, screen_height))
        # 获取图片的大小
        image_width, image_height = image.get_size()
        # 计算图片在窗口中的位置
        image_x = (screen_width - image_width) // 2
        image_y = (screen_height - image_height) // 2
        # 在窗口中央显示图片
        screen.blit(image, (image_x, image_y))
    # 获取按键
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        aircraft_rect.x -= aircraft_speed
    if keys[pygame.K_RIGHT]:
        aircraft_rect.x += aircraft_speed
    if keys[pygame.K_UP]:
        aircraft_rect.y -= aircraft_speed
    if keys[pygame.K_DOWN]:
        aircraft_rect.y += aircraft_speed

    # 限制飞机移动范围
    if aircraft_rect.x < 0:
        aircraft_rect.x = 0
    if aircraft_rect.x > screen_width - aircraft_rect.width:
        aircraft_rect.x = screen_width - aircraft_rect.width
    if aircraft_rect.y < 0:
        aircraft_rect.y = 0
    if aircraft_rect.y > screen_height - aircraft_rect.height:
        aircraft_rect.y = screen_height - aircraft_rect.height

    # 敌机移动
    enemy_rect.y += enemy_speed
    if enemy_rect.y > screen_height:
        enemy_rect.x = random.randint(0, screen_width - enemy_rect.width)
        enemy_rect.y = -enemy_rect.height

# 退出游戏
pygame.quit()















